package vue;



import java.util.LinkedList;

import modele.Chat;
import modele.CoreData;
import modele.SimpleService;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.example.finalprojet.R;


@SuppressLint("HandlerLeak")
public class ChatBox extends Activity {
	

	
	int smsiphone;
	SoundPool wmp;
	ScrollView scroll;
	LinearLayout ChatMessage;
	String pseudo = null;
	Messenger mService = null;	Button envoyer = null;
	EditText message = null;
	LinkedList<String> allmessage = null;
	//private String Constant = null;
	
	
	@Override
	protected void onStop() {
		super.onStop();
		
		CoreData donnéechat = (CoreData)getApplication();
		

		Chat c = new Chat(pseudo, getIntent().getStringExtra("id"), allmessage);
		
		donnéechat.ajouterchat(c);
		
		
	}


	final Messenger mMessenger = new Messenger(new IncomingHandler());
	
	  private ServiceConnection mConnection = new ServiceConnection() {


			public void onServiceConnected(ComponentName arg0, IBinder arg1) {

	            mService = new Messenger(arg1);
	           
	            try {
	                Message msg = Message.obtain(null, SimpleService.MSG_REGISTER_CLIENT);
	                msg.replyTo = mMessenger;
	                mService.send(msg);
	                addroom("chat%00%" + getIntent().getStringExtra("pseudomoi") + "%" + pseudo);
	             
	            } catch (RemoteException e) {
	            }
				
			}

			public void onServiceDisconnected(ComponentName name) {
				//mService = null;
				
			}
	    };
	
	protected void onCreate(Bundle savedInstanceState) {
		
	super.onCreate(savedInstanceState);
	setContentView(R.layout.chatlayout);
	
	allmessage = new LinkedList<String>();
	wmp = new SoundPool(16, AudioManager.STREAM_MUSIC, 0);
	smsiphone = wmp.load(getApplicationContext(), R.raw.iphone_sms_original, 1);		
	envoyer = (Button)findViewById(R.id.chatlayoutenvoyer);
	message = (EditText)findViewById(R.id.chatlayoutmessage);
	ChatMessage = ( LinearLayout)findViewById(R.id.chatlayoutlstmessage);
	scroll = ( ScrollView)findViewById(R.id.scrollView1);
	pseudo = getIntent().getStringExtra("pseudo");

	CoreData donnéechat = (CoreData)getApplication();
	
	
	try
	{
		
	
	
	Chat c = donnéechat.getchatnumberi(getIntent().getStringExtra("id"));	
	restaureChat(c);
	this.allmessage = c.getMessage();
	
	
	}catch (Exception e){e.printStackTrace();}
	
	  bindService(new Intent(this, SimpleService.class), mConnection, Context.BIND_AUTO_CREATE);
	  
	  
	envoyer.setOnClickListener(new OnClickListener() {
		
		public void onClick(View v) {
	
			    
			    sendMessageToService(message.getText().toString());
			    TextView Nextmess = new TextView(ChatBox.this);
                Nextmess.setBackgroundResource(R.drawable.rounded_to);
                Nextmess.setText(message.getText());
                Nextmess.setGravity(Gravity.LEFT);
                Nextmess.setPadding(5, 10, 5, 10);
                Nextmess.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                ChatMessage.addView(Nextmess);
			    scroll.fullScroll(ScrollView.FOCUS_DOWN);
			    allmessage.add("t"+message.getText().toString());
			    //message.setText(allmessage.size());
			    
			    for ( int t = 0 ; t <allmessage.size() ; t++)
			    {
			    	Log.e(String.valueOf(t),allmessage.get(t).toString());
			    }
		}
	});
	
	
	
	
	}
	
	
	 private void restaureChat(Chat tabchat) {
		 
		 for ( int i = 0 ; i < tabchat.getMessage().size() ; i++)
		 {
			 TextView Nextmess = new TextView(ChatBox.this);
			 if ( tabchat.getMessage().get(i).startsWith("t"))
			 {
			 Nextmess.setBackgroundResource(R.drawable.rounded_to);
			 Nextmess.setGravity(Gravity.LEFT);
			 }
			 else 
			 {
				 Nextmess.setBackgroundResource(R.drawable.rounded_from); 
				 Nextmess.setGravity(Gravity.RIGHT);
			 }
			 Nextmess.setText(tabchat.getMessage().get(i));
	         
	         Nextmess.setPadding(5, 10, 5, 10);
	         Nextmess.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
	         ChatMessage.addView(Nextmess);  
		 }

		 scroll.fullScroll(ScrollView.FOCUS_DOWN);
		 message.setText("");
		
	}


	private void sendMessageToService(String message) {
			

             Bundle b = new Bundle();
				b.putString("str1",message);
				Message msg = Message.obtain(null, SimpleService.MSG_SET_STRING_VALUE);
				msg.setData(b);
				try{
					
					mService.send(msg);
					
				}catch(Exception e){e.printStackTrace();}
  
 }
	 
	 private void addroom(String message) {
			

         Bundle b = new Bundle();
			b.putString("str1",message);
			Message msg = Message.obtain(null, SimpleService.MSG_ADD_CHAT_ROOM);
			msg.setData(b);
			try{
				
				mService.send(msg);
				
			}catch(Exception e){e.printStackTrace();}

}
	 
	class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            
            case SimpleService.MSG_SET_STRING_VALUE:
            	wmp.play(smsiphone, 1, 1, 1, 0, 1);
                String str1 = msg.getData().getString("str1");
                TextView Nextmess = new TextView(ChatBox.this);
                Nextmess.setBackgroundResource(R.drawable.rounded_from);
                Nextmess.setText(str1);
                Nextmess.setPadding(5, 10, 5, 10);
                LinearLayout.LayoutParams param= new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                param.gravity=Gravity.RIGHT;
                Nextmess.setHapticFeedbackEnabled(true);
                Nextmess.setLayoutParams(param); 
                ChatMessage.addView(Nextmess);
                 scroll.fullScroll(ScrollView.FOCUS_DOWN);
                 allmessage.add("f"+str1);
                break;
                
          
            	
        default:
                super.handleMessage(msg);
            }
        
    }
	

}
	
	
	
	
	
	}
